#!/bin/bash

set -e

cat<<EOF

#######################################
#  INSTALL APP 
#######################################

EOF
function make_swap () {
	local DISK_REQUIREMENTS=6144; #6Gb free space
	local MEMORY_REQUIREMENTS=11000; #RAM ~12Gb

	local AVAILABLE_DISK_SPACE=$(df -m /  | tail -1 | awk '{ print $4 }');
	local TOTAL_MEMORY=$(free -m | grep -oP '\d+' | head -n 1);
	local EXIST=$(swapon -s | awk '{ print $1 }' | { grep -x '/app_swapfile' || true; });

	if [[ -z $EXIST ]] && [ ${TOTAL_MEMORY} -lt ${MEMORY_REQUIREMENTS} ] && [ ${AVAILABLE_DISK_SPACE} -gt ${DISK_REQUIREMENTS} ]; then
		dd if=/dev/zero of=/app_swapfile count=6144 bs=1MiB
		chmod 600 /app_swapfile
		mkswap /app_swapfile
		swapon /app_swapfile
		echo "/app_swapfile none swap sw 0 0" >> /etc/fstab
	fi
}

if [ -e /etc/redis.conf ]; then
	sed -i "s/bind .*/bind 127.0.0.1/g" /etc/redis.conf
	sed -r "/^save\s[0-9]+/d" -i /etc/redis.conf
	
	systemctl restart redis
fi

sed "/host\s*all\s*all\s*127\.0\.0\.1\/32\s*ident$/s|ident$|trust|" -i /var/lib/pgsql/data/pg_hba.conf
sed "/host\s*all\s*all\s*::1\/128\s*ident$/s|ident$|trust|" -i /var/lib/pgsql/data/pg_hba.conf

for SVC in $package_services; do
		systemctl start $SVC
		systemctl enable $SVC
done

if [ "$UPDATE" = "true" ]; then
	if [ "$OPENSOURCE" = "true" ]; then
		${package_manager} -y update ${package_sysname}-documentserver
		${package_manager} -y update ${package_sysname}-communityserver
	else
		${package_manager} -y update ${package_sysname}-controlpanel
		${package_manager} -y update ${package_sysname}-documentserver-ie
		${package_manager} -y update ${package_sysname}-communityserver	
	fi
	
	exit;
fi

MYSQL_SERVER_HOST=${MYSQL_SERVER_HOST:-"localhost"}
MYSQL_SERVER_DB_NAME=${MYSQL_SERVER_DB_NAME:-"${package_sysname}"}
MYSQL_SERVER_USER=${MYSQL_SERVER_USER:-"root"}
MYSQL_SERVER_PASS=${MYSQL_SERVER_PASS:-"bbThb75KEvbxczk2019!"}
MYSQL_SERVER_PORT=${MYSQL_SERVER_PORT:-3306}

MYSQL_TEMPORARY_ROOT_PASS="";

if [ -f "/var/log/mysqld.log" ]; then
	MYSQL_TEMPORARY_ROOT_PASS=$(cat /var/log/mysqld.log | grep "temporary password" | rev | cut -d " " -f 1 | rev | tail -1);
fi

while ! mysqladmin ping -u root --silent; do
   		sleep 1
done

if ! mysql "-u$MYSQL_SERVER_USER" "-p$MYSQL_SERVER_PASS" -e ";" >/dev/null 2>&1; then

	if [ -z $MYSQL_TEMPORARY_ROOT_PASS ]; then
	   MYSQL="mysql --connect-expired-password -u$MYSQL_SERVER_USER -D mysql";
	else
	   MYSQL="mysql --connect-expired-password -u$MYSQL_SERVER_USER -p${MYSQL_TEMPORARY_ROOT_PASS} -D mysql";
	fi

   $MYSQL -e "ALTER USER '${MYSQL_SERVER_USER}'@'localhost' IDENTIFIED WITH mysql_native_password BY '${MYSQL_SERVER_PASS}'" >/dev/null 2>&1 \
   || $MYSQL -e "UPDATE user SET plugin='mysql_native_password', authentication_string=PASSWORD('${MYSQL_SERVER_PASS}') WHERE user='${MYSQL_SERVER_USER}' and host='localhost';"		

	systemctl restart mysqld

fi

#expect << EOF
#spawn mysql_config_editor set --login-path=${package_sysname} --host=$MYSQL_SERVER_HOST --user=$MYSQL_SERVER_USER --password
#expect -nocase "Enter password:" {send "${MYSQL_SERVER_PASS}\r"; interact}
#EOF


if [ "$DOCUMENT_SERVER_INSTALLED" = "false" ]; then
	declare -x DS_PORT=8083

	DS_RABBITMQ_HOST=localhost;
	DS_RABBITMQ_USER=guest;
	DS_RABBITMQ_PWD=guest;
	
	DS_REDIS_HOST=localhost;
	
	DS_COMMON_NAME=${DS_COMMON_NAME:-"ds"};

	DS_DB_HOST=localhost;
	DS_DB_NAME=$DS_COMMON_NAME;
	DS_DB_USER=$DS_COMMON_NAME;
	DS_DB_PWD=$DS_COMMON_NAME;
	
	declare -x JWT_ENABLED=true;
	declare -x JWT_SECRET="secret";
	declare -x JWT_HEADER="Authorization";
		
	if ! su - postgres -s /bin/bash -c "psql -lqt" | cut -d \| -f 1 | grep -q ${DS_DB_NAME}; then
		su - postgres -s /bin/bash -c "psql -c \"CREATE DATABASE ${DS_DB_NAME};\""
		su - postgres -s /bin/bash -c "psql -c \"CREATE USER ${DS_DB_USER} WITH password '${DS_DB_PWD}';\""
		su - postgres -s /bin/bash -c "psql -c \"GRANT ALL privileges ON DATABASE ${DS_DB_NAME} TO ${DS_DB_USER};\""
	fi
	
	if [ "$OPENSOURCE" = "true" ]; then
		${package_manager} -y install ${package_sysname}-documentserver
	else
	
		${package_manager} -y install ${package_sysname}-documentserver-ie
	fi

	systemctl restart supervisord
	
expect << EOF
	
	set timeout -1
	log_user 1
	
	spawn documentserver-configure.sh
	
	expect "Configuring database access..."
	
	expect -re "Host"
	send "\025$DS_DB_HOST\r"
	
	expect -re "Database name"
	send "\025$DS_DB_NAME\r"
	
	expect -re "User"
	send "\025$DS_DB_USER\r"
	
	expect -re "Password"
	send "\025$DS_DB_PWD\r"
	
	expect "Configuring redis access..."
	send "\025$DS_REDIS_HOST\r"
	
	expect "Configuring AMQP access... "
	expect -re "Host"
	send "\025$DS_RABBITMQ_HOST\r"
	
	expect -re "User"
	send "\025$DS_RABBITMQ_USER\r"
	
	expect -re "Password"
	send "\025$DS_RABBITMQ_PWD\r"
	
	expect eof
	
EOF
	
	systemctl restart nginx
	systemctl enable supervisord
	systemctl enable nginx

	DOCUMENT_SERVER_INSTALLED="true";
fi

if [ "$CONTROL_PANEL_INSTALLED" = "false" ] && [ "$OPENSOURCE" != "true" ]; then

	declare -x CONTROLPANEL_DB_PORT=${CONTROLPANEL_DB_PORT:8082}

	${package_manager} -y install ${package_sysname}-controlpanel

	CONTROL_PANEL_INSTALLED="true";
fi

if [ "$COMMUNITY_SERVER_INSTALLED" = "false" ]; then

	CS_DB_HOST=${MYSQL_SERVER_HOST};
	CS_DB_NAME=${MYSQL_SERVER_DB_NAME};
	CS_DB_USER=${MYSQL_SERVER_USER};
	CS_DB_PWD=${MYSQL_SERVER_PASS};

	${package_manager} -y install ${package_sysname}-communityserver
	
expect << EOF
	
	set timeout -1
	log_user 1
	
	spawn communityserver-configure.sh
	
	expect -re "Host"
	send "\025$CS_DB_HOST\r"
	
	expect -re "Database name"
	send "\025$CS_DB_NAME\r"
	
	expect -re "User"
	send "\025$CS_DB_USER\r"
	
	expect -re "Password"
	send "\025$CS_DB_PWD\r"
	
	expect eof
	
EOF

COMMUNITY_SERVER_INSTALLED="true";

fi

NGINX_ROOT_DIR="/etc/nginx"

if [ "$REV" = "8" ]; then
	cp -f ${NGINX_ROOT_DIR}/includes/${package_sysname}-communityserver-nginx.conf.template ${NGINX_ROOT_DIR}/nginx.conf
fi

NGINX_WORKER_PROCESSES=${NGINX_WORKER_PROCESSES:-$(grep processor /proc/cpuinfo | wc -l)};
NGINX_WORKER_CONNECTIONS=${NGINX_WORKER_CONNECTIONS:-$(ulimit -n)};

sed 's/^worker_processes.*/'"worker_processes ${NGINX_WORKER_PROCESSES};"'/' -i ${NGINX_ROOT_DIR}/nginx.conf
sed 's/worker_connections.*/'"worker_connections ${NGINX_WORKER_CONNECTIONS};"'/' -i ${NGINX_ROOT_DIR}/nginx.conf

make_swap

if rpm -q "firewalld"; then
	firewall-cmd --permanent --zone=public --add-service=http || true
	firewall-cmd --permanent --zone=public --add-service=https || true
	systemctl restart firewalld.service || true
fi

systemctl restart nginx

echo ""
echo "${RES_INSTALL_SUCCESS}"

if [ "$OPENSOURCE" != "true" ]; then
	echo "$RES_RES_PROPOSAL"
fi

echo "$RES_QUESTIONS"
echo ""